package com.snack.shop.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.snack.shop.common.Result;
import com.snack.shop.dto.LoginParam;
import com.snack.shop.dto.RegisterParam;
import com.snack.shop.dto.WxLoginRequest;
import com.snack.shop.dto.WxLoginParam;
import com.snack.shop.entity.User;
import com.snack.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Tag(name = "用户管理")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@Validated @RequestBody RegisterParam param) {
        String token = userService.register(param);
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        return Result.success(result);
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Validated @RequestBody LoginParam param) {
        String token = userService.login(param);
        
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        
        return Result.success(result);
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public Result<User> getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getUserById(userId);
        return Result.success(user);
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public Result<Void> logout() {
        StpUtil.logout();
        return Result.success();
    }
    
    @Operation(summary = "获取微信openid")
    @PostMapping("/wx/openid")
    public Result<Map<String, String>> getWxOpenid(@Validated @RequestBody WxLoginRequest request) {
        String openid = userService.getAndSaveOpenid(request.getCode());
        
        Map<String, String> result = new HashMap<>();
        result.put("openid", openid);
        
        return Result.success(result);
    }

    @Operation(summary = "更新用户资料")
    @PostMapping("/update")
    public Result<Void> updateProfile(@Validated @RequestBody com.snack.shop.dto.UserUpdateRequest request) {
        Long userId = StpUtil.getLoginIdAsLong();
        userService.updateProfile(userId, request);
        return Result.success();
    }

    @Operation(summary = "微信一键登录")
    @PostMapping("/wx/login")
    public Result<Map<String, Object>> wxLogin(@Validated @RequestBody WxLoginParam param) {
        Map<String, Object> loginResult = userService.wxLogin(param);
        return Result.success(loginResult);
    }
}

